<?php

namespace common\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\User;

/**
 * UserSearch represents the model behind the search form about `common\models\User`.
 */
class UserSearch extends User
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'role', 'status', 'created_at', 'updated_at'], 'integer'],
            [['username', 'auth_key', 'password_hash', 'password_reset_token', 'email'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = User::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pagesize' => $params['defaultPageSize'],
            ]
        ]);

        if (isset($params['role']) && $params['role'] != '') {
            $query->andFilterWhere(['=', 'role', $params['role']]);
        }

        if (isset($params['status']) && $params['status'] != '') {
            $query->andFilterWhere(['=', 'status', $params['status']]);
        }

        if (!empty($params['username'])){
            $query->andFilterWhere(['like', 'username', $params['username']]);
        }

        if (!empty($params['email'])){
            $query->andFilterWhere(['like', 'email', $params['email']]);
        }

        return $dataProvider;
    }
}
